import React, { memo, Component } from 'react'
import _ from 'lodash'
import './index.css'
import { message } from 'antd'

class TextFlow extends Component {
  constructor(props) {
    super(props)
    this.state = {
      detail: props.text, //文本内容
      clamp: props.clamp || 1, //文本最多显示几行
      clientX: null, //鼠标X坐标
      clientY: null, //鼠标Y坐标
      visible: false, //FLow框是否可见
      color: props.color || 'rgb(255, 101, 101)', //Flow框阴影色
      colorful: props.colorful || true, //Flow框随机变色
      width: props.width || 400, //Flow框宽度
      realWidth: props.width || 400 //Flow框实际宽度
    }
  }

  getRandomColor = () => {
    return `rgb(${parseInt(Math.random() * 255)},${parseInt(
      Math.random() * 255
    )},${parseInt(Math.random() * 255)})`
  }

  /* 监听鼠标移动 */
  listenMouseMove = (window) => {
    const { width } = this.state
    if (window.view.innerWidth - window.pageX < width)
      this.setState({
        realWidth: window.view.innerWidth - window.pageX - 25
      })
    else
      this.setState({
        realWidth: width
      })
    // console.log(window.view.innerWidth - window.pageX);
    // console.log(window.event);

    // if(window.pageY <100)
    //   return
    // console.log(
    //   `鼠标x坐标：${window.pageX}    鼠标y坐标：${window.pageY}`
    // )
    this.setState({
      clientX: window.pageX + 15,
      clientY: window.nativeEvent.layerY + 15,
      visible: true
    })
  }

  /* 点击复制内容 */
  copyContent = () => {
    const {detail} = this.state
    let inputElement = document.getElementById('copy_content')
    inputElement.value = detail
    inputElement.select()
    document.execCommand('Copy')
    message.success('已复制')
  }

  render() {
    const {
      detail,
      clientX,
      clientY,
      visible,
      clamp,
      color,
      colorful,
      width,
      realWidth
    } = this.state
    return (
      <div
        onMouseMove={_.debounce((window) => this.listenMouseMove(window), 50)}
        className="TextFlow"
        style={{
          WebkitLineClamp: clamp,
        }}
        onMouseLeave={_.debounce(() => {
          this.setState({ visible: false })
        }, 60)}
        onClick={this.copyContent.bind(this)}
      >
        {detail}
        <div
          className="FlowBox"
          style={{
            position: 'absolute',
            top: clientY,
            left: clientX,
            display: visible ? 'block' : 'none',
            maxWidth: width,
            width: realWidth
          }}
        >
          {detail}
        </div>
        <input
          id="copy_content"
          type="text"
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            opacity: 0,
            zIndex: -10
          }}
        />
      </div>
    )
  }
}
export default TextFlow
